import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/models/store_index.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';

/// 店铺首页
class StoreIndexModel extends ViewModel {
  final Api api;
  final int bindingStoreId;
  int _storeId;
  String _errorMessage;
  StoreIndex _storeIndex;

  StoreIndexModel(this.api, this.bindingStoreId) : super();

  set storeId(int value) {
    debugPrint('$this set storeId = $value');
    if (_storeId != value) {
      _storeId = value;
      _initData();
    }
  }

  String get errorMessage => _errorMessage;

  StoreIndex get storeIndex => _storeIndex;

  Future<ViewState> _initData() async {
    viewState = ViewState.busy;
    try {
      _storeIndex = await api.storeIndex(bindingStoreId, _storeId, cancelToken);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
